<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      size="small"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="100px"
    >
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type" :disabled="menuDisabledType">
          <el-radio
            v-for="(type, index) in typeList"
            :label="index"
            :key="index"
            >{{ type }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="typeList[dataForm.type] + '名称'" prop="name">
        <el-input
          v-model="dataForm.name"
          :placeholder="typeList[dataForm.type] + '名称'"
        ></el-input>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
          ref="menuListPopover"
          placement="bottom-start"
          trigger="click"
        >
          <el-tree
            :data="menuList"
            :props="menuListTreeProps"
            node-key="id"
            ref="menuListTree"
            @current-change="menuListTreeCurrentChangeHandle"
            :default-expand-all="false"
            :highlight-current="true"
            :expand-on-click-node="false"
          >
          </el-tree>
        </el-popover>
        <el-input
          v-model="dataForm.parentName"
          v-popover:menuListPopover
          :readonly="true"
          placeholder="点击选择上级菜单"
          class="menu-list__input"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="菜单路由" prop="url">
        <el-input v-model="dataForm.url" placeholder="菜单路由"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 0" label="授权标识" prop="perms">
        <el-input
          v-model="dataForm.perms"
          placeholder="授权标识， 如: user:list"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="dataForm.type !== 2" label="是否外链">
        <el-switch
          v-model="dataForm.outLink"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="是"
          inactive-text="否"
        >
        </el-switch>
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 2 && dataForm.outLink"
        label="外链地址"
        prop="outLinkUrl"
      >
        <el-input
          v-model="dataForm.outLinkUrl"
          placeholder="外链地址"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="dataForm.type !== 2" label="菜单图标" prop="icon">
        <el-row>
          <el-col :span="22">
            <el-popover
              ref="iconListPopover"
              placement="bottom-start"
              trigger="click"
              popper-class="mod-menu__icon-popover"
            >
              <div class="mod-menu__icon-inner">
                <div class="mod-menu__icon-list">
                  <el-button
                    v-for="(item, index) in iconList"
                    :key="index"
                    @click="iconActiveHandle(item)"
                    :class="{ 'is-active': item === dataForm.icon }"
                  >
                    <icon-svg :name="item"></icon-svg>
                  </el-button>
                </div>
              </div>
            </el-popover>
            <el-input
              v-model="dataForm.icon"
              v-popover:iconListPopover
              :readonly="true"
              placeholder="菜单图标名称"
              class="icon-list__input"
            ></el-input>
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light">
              <div slot="content">
                全站推荐使用SVG Sprite, 详细请参考:<a
                  href="//github.com/daxiongYang/renren-fast-vue/blob/master/src/icons/index.js"
                  target="_blank"
                  >icons/index.js</a
                >描述
              </div>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>

      <el-form-item label="排序号" prop="orderNum">
        <el-input-number
          v-model="dataForm.orderNum"
          controls-position="right"
          :min="0"
          label="排序号"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="visible = false">取消</el-button>
      <el-button size="small" type="primary" @click="dataFormSubmit()"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
import Icon from "@/icons";
import { getMenuTop, saveAndUpdate } from "@/api/menu";

export default {
  data() {
    var validateUrl = (rule, value, callback) => {
      if (this.dataForm.type === 1 && !/\S/.test(value)) {
        callback(new Error("菜单URL不能为空"));
      } else {
        callback();
      }
    };
    var validateOutLinkUrl = (rule, value, callback) => {
      if (
        this.dataForm.type != 2 &&
        !/\S/.test(value) &&
        this.dataForm.outLink
      ) {
        callback(new Error("外链地址不能为空"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      typeList: ["目录", "菜单", "按钮"],
      iconList: [],
      menuDisabledType: false,
      dataForm: {
        id: 0,
        type: 1,
        name: "",
        parentId: 0,
        parentName: "",
        url: "",
        perms: "",
        remark: "",
        orderNum: 0,
        outLink: false,
        outLinkUrl: "",
        icon: "",
      },
      dataRule: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        perms: [
          { required: true, message: "授权标识不能为空", trigger: "blur" },
        ],
        url: [{ validator: validateUrl, trigger: "blur" }],
        outLinkUrl: [{ validator: validateOutLinkUrl, trigger: "blur" }],
      },
      menuList: [],
      menuListTreeProps: {
        label: "name",
        children: "children",
      },
    };
  },
  created() {
    this.iconList = Icon.getNameList();
  },
  methods: {
    init(data) {
      this.dataForm.id = 0;
      this.menuDisabledType = false;
      getMenuTop()
        .then((res) => {
          if (res && res.code === 0) {
            this.menuList = treeDataTranslate(res.data, "id");
          }
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (data) {
            if (data.addChildren == 1) {
              this.dataForm.parentId = data.id;
              // 新增
              this.menuListTreeSetCurrentNode();
              // 新增
            } else if (data.addChildren == 2) {
              // 修改
              this.menuDisabledType = true;
              this.dataForm.id = data.id;
              this.dataForm.type = data.type;
              this.dataForm.name = data.name;
              this.dataForm.parentId = data.parentId;
              this.dataForm.url = data.url;
              this.dataForm.perms = data.perms;
              this.dataForm.orderNum = data.orderNum;
              this.dataForm.icon = data.icon;
              this.dataForm.outLink = data.outLink || false;
              this.dataForm.outLinkUrl = data.outLinkUrl || "";
              this.dataForm.remark = data.remark;
              this.menuListTreeSetCurrentNode();
            }
          }
        });
    },
    // 菜单树选中
    menuListTreeCurrentChangeHandle(data, node) {
      this.dataForm.parentId = data.id;
      this.dataForm.parentName = data.name;
    },
    // 菜单树设置当前选中节点
    menuListTreeSetCurrentNode() {
      this.$refs.menuListTree.setCurrentKey(this.dataForm.parentId);
      this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() ||
        {})["name"];
    },
    // 图标选中
    iconActiveHandle(iconName) {
      this.dataForm.icon = iconName;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          saveAndUpdate(this.dataForm).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.mod-menu {
  .menu-list__input,
  .icon-list__input {
    > .el-input__inner {
      cursor: pointer;
    }
  }
  &__icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &__icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &__icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
  .icon-list__tips {
    font-size: 18px;
    text-align: center;
    color: #e6a23c;
    cursor: pointer;
  }
}
</style>
